import { defineStore } from 'pinia'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/storage'
import type { UserInfo } from '@/utils/storage'
import request from '@/utils/request'

interface UserState {
  token: string
  userInfo: UserInfo | null
  roles: string[]
  permissions: string[]
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: getToken(),
    userInfo: getUserInfo(),
    roles: getUserInfo()?.role ? [getUserInfo()?.role || ''] : [],
    permissions: getUserInfo()?.permissions || [],
  }),
  
  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,
    // 获取用户角色
    userRoles: (state) => state.roles,
    // 获取用户权限
    userPermissions: (state) => state.permissions,
  },
  
  actions: {
    // 用户登录
    async login(username: string, password: string) {
      try {
        const response = await request.post<{
          code: number
          data: {
            id: number
            token: string
            userName: string
            realName: string
            role: string
          }
          message: string
        }>('/authUser/doLogin', { username, password })
        
        // 确保正确获取后端返回的数据
        if (response.code !== 200 || !response.data) {
          return Promise.reject(new Error(response.message || '登录失败'))
        }
        
        const data = response.data
        
        // 构造用户信息对象
        const userInfo: UserInfo = {
          id: data.id,
          userName: data.userName,
          realName: data.realName,
          role: data.role,
          token: data.token
        }
        
        this.token = data.token
        this.userInfo = userInfo
        this.roles = [data.role]
        this.permissions = []
        
        // 保存到本地存储
        setToken(data.token)
        setUserInfo(userInfo)
        
        return response
      } catch (error) {
        console.error('登录失败', error)
        return Promise.reject(error)
      }
    },
    
    // 用户登出
    async logout() {
      try {
      } catch (error) {
        console.error('Logout error:', error)
      } finally {
        // 清除Token和用户信息
        this.resetState()
      }
    },
    
    // 重置状态
    resetState() {
      this.token = ''
      this.userInfo = null
      this.roles = []
      this.permissions = []
      removeToken()
      removeUserInfo()
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        const userId = this.userInfo?.id
        if (!userId) {
          return Promise.reject(new Error('用户ID不存在'))
        }
        
        const response = await request.get<{
          code: number
          data: UserInfo
          message: string
        }>(`/authUser/get/${userId}`)
        
        const userInfo = response.data
        this.userInfo = userInfo
        this.roles = [userInfo.role]
        this.permissions = userInfo.permissions || []
        
        // 更新本地存储
        setUserInfo(userInfo)
        
        return userInfo
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 更新用户信息
    updateUserInfo(userInfo: Partial<UserInfo>) {
      if (this.userInfo) {
        this.userInfo = { ...this.userInfo, ...userInfo }
        setUserInfo(this.userInfo)
      }
    },
  },
}) 